package com.sumainfor.pc.gmio.service.impl;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.gmio.dao.HoGasMeterMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.BillOwnerMapper;
import com.sumainfor.pc.gmio.dao.SeTenantBillMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZwxTenantFeign;
import com.sumainfor.pc.gmio.service.SeGasMeterExtService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.management.relation.Relation;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zc
 * @ClassName SeGasMeterExtServiceImpl
 * @date 2019/11/21 14:41
 * @description: TODO
 */
@Service
public class SeGasMeterExtServiceImpl implements SeGasMeterExtService {
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(SeGasMeterExtServiceImpl.class);


    @Autowired
    ZpcMktFeign zpcMktFeign;
    @Autowired
    HoGasMeterMapper hoGasMeterMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    BillOwnerMapper billOwnerMapper;

    @Autowired
    SeTenantBillMapper seTenantBillMapper;

    @Autowired
    ZwxTenantFeign zwxTenantFeign;

    /**
     * 关机抄表是需要抄燃气表的房源,及其上一次最近的抄表数
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getGasMeterNum(Map<String, Object> params, Pager pager) {
        JsonResult MktFeign = zpcMktFeign.getPactNumHou(params,pager);//获取需要管家抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if(MktList.size()>0){
            for (Map<String,Object> map1:MktList){
                Map<String,Object> hoWaterMeterMap = hoGasMeterMapper.getHouInfoGas(map1);//查询当前房源的最近一次的抄表数;
                if (hoWaterMeterMap!=null) {
                    map1.putAll(hoWaterMeterMap);
                }
            }
        }

        return MktFeign;
    }

    /**
     * 秘书抄房源下的燃气
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getGasSecretary(Map<String, Object> params, Pager pager) {
        JsonResult MktFeign = zpcMktFeign.getHouId(params,pager);//获取需要秘书抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if(MktList.size()>0){
            for (Map<String,Object> map1:MktList){
                map1.put("MeterRole",1);
                Map<String,Object> getHouInfoGas = hoGasMeterMapper.getHouInfoGas(map1);//查询当前房源的最近一次的抄表数;
                if (getHouInfoGas!=null) {
                    map1.putAll(getHouInfoGas);
                }
                String a = MapUtils.getString(map1,"HouInfoId");
                map1.put("HouInfoId",a.replace(a.substring(a.length() - 1, a.length()), "Z"));
            }
        }
        return MktFeign;

    }

    /**
     * 秘书记录抄表燃气表数
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult addGasClerk(Map<String, Object> params) {
        JsonResult result = new JsonResult();
//
//        参数格式
//                params:{
//                 "GasHouList":[
//                    {
//                        HouId
//                        HouInfoId
//                        LastMonthRead
//                        ThisMonthRead
//                        StaTime
//                        EndTime
//                        BillMoney
//                    },
//                    {
//                        HouId
//                         HouInfoId
//                        LastMonthRead
//                        ThisMonthRead
//                        StaTime
//                         EndTime
//                        BillMoney
//                    }
//
//
//
//
//
//
//                         ]
//
//
//                }




        lock.lock();
        try {

//           String BiOutIdUUID = "";//账单支出编号
//           String  BiIdUUID ="";//租客编号
//            String GasmeIdUUID = "";//燃气抄表编号
//            String BatchIdUUID = "";//燃气抄表批次编号
//            String BiOutIdUUID = "";//账单支出编号
//            Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiOutId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_bill_outlay");
//            }});
//            String  BiIdUUID ="";//租客编号
//            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_tenant_bill");
//            }});


//            String GasmeIdUUID = "";//燃气抄表编号
//            String BatchIdUUID = "";//燃气抄表批次编号
//            Map<String, Object> GasmeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "GasmeId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_gas_meter");
//            }});
//
//
//            if(GasmeIduuid!=null){
//                int number=Integer.valueOf(GasmeIduuid.get("uuid").toString());
//                GasmeIdUUID= ComUtils.getLocalTrmSeqNum("GM0",number);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
//            }else{
//                GasmeIdUUID=ComUtils.getLocalTrmSeqNum("GM0",0);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
//            }

            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimes = sdf.format(nowTime);//记录当前时间


             Integer a = new Integer("0");
            List<Map<String,Object>> GasHouList = (List<Map<String, Object>>) params.get("GasHouList");//获取本次记录的房源燃气表集合
            if (GasHouList.size()>0){
                for (Map<String,Object> GasHouMap:GasHouList){


                    String GasmeIdUUID = "";//燃气抄表编号
                    String BatchIdUUID = "";//燃气抄表批次编号
                    Map<String, Object> GasmeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "GasmeId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_gas_meter");
                    }});


                    if(GasmeIduuid!=null){
                        int number=Integer.valueOf(GasmeIduuid.get("uuid").toString());
                        GasmeIdUUID= ComUtils.getLocalTrmSeqNum("GM0",number);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
                    }else{
                        GasmeIdUUID=ComUtils.getLocalTrmSeqNum("GM0",0);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }






                    Integer aaa = new Integer("0");



                    Double GasBiMoney = new Double("0");
                    //获取当前房源签署的公司号
                    JsonResult CorIdResult = zpcMktFeign.getCorId(GasHouMap);
                    Map<String,Object> CorIdMap = (Map<String, Object>) CorIdResult.get("result");



                   JsonResult MktResult = zpcMktFeign.getInfoStatus(GasHouMap);
                   Map<String,Object> getInfoMap = (Map<String, Object>) MktResult.get("result");

                    Map<String,Object> OutLaymap = new HashMap<>();
                    String BiOutIdUUID = "";//账单支出编号
                    Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiOutId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_outlay");
                    }});
                    if(BiOutIduuid!=null){
                        int numberss=Integer.valueOf(BiOutIduuid.get("uuid").toString());
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcGas",numberss);
                    }else{
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcGas",0);
                    }
                    OutLaymap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    OutLaymap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(OutLaymap);
                    OutLaymap.put("BiOutId",BiOutIdUUID);//账单编号
                    OutLaymap.put("CorId",CorIdMap.get("CorId"));//归属公司
                    OutLaymap.put("Period",1);//账期
                    OutLaymap.put("BiOutName","秘书抄表生成燃气账单");//账单名称
                    OutLaymap.put("IfTemporary",0);//0否临时账单 1是
                    OutLaymap.put("BiOutType",4);//4账单类型 公共事业费
                    OutLaymap.put("PubType",3);//燃气费
                    OutLaymap.put("BillExplain","秘书抄表生成燃气账单");//金额说明
                    OutLaymap.put("StartTime",GasHouMap.get("StaTime"));//账单生成日
                    OutLaymap.put("EndTime",GasHouMap.get("EndTime"));//账单结束日
                    OutLaymap.put("LateDay",GasHouMap.get("EndTime"));//账单最晚付款日
                    OutLaymap.put("IfAdjust",0);//当前账单是否可以调整0否
                    OutLaymap.put("StemType",3);//支出类型 3租客
                    OutLaymap.put("HouId",GasHouMap.get("HouId"));//房源id
                    OutLaymap.put("HouInfoId",GasHouMap.get("HouInfoId"));//房源详表编号
                    OutLaymap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    OutLaymap.put("Applicant", ContextUtils.getUserId());//申请人
                    OutLaymap.put("Status",1);//账单状态1待支付


                    Map<String,Object> billMap = new HashMap<>();
                    String  BiIdUUID ="";//租客编号
                    Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});
                    if(BiIduuid!=null){
                        int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIGASMS",number);
                    }else{
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIGASMS",0);
                    }
                    billMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    billMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(billMap);
                    billMap.put("BiId",BiIdUUID);//账单编号
                    billMap.put("CorId",CorIdMap.get("CorId"));//账单归属公司
                    billMap.put("BiName","秘书抄表生成租客燃气账单");//账单名称
                    billMap.put("IfTemporary",0);//是否是临时账单0否 1 是
                    billMap.put("BiType",2);//账单类型 2公共事业费
                    billMap.put("PubType",3);//公共事业费类型1水费 2电费 3燃气
                    billMap.put("BillExplain","秘书抄表生成租客燃气费账单");//账单金额说明
                    billMap.put("BiGenerated",GasHouMap.get("StaTime"));//账单生成日
                    billMap.put("EndTime", GasHouMap.get("EndTime"));//账单结束日
                    billMap.put("LateDay", GasHouMap.get("EndTime"));//账单最晚付款日
                    billMap.put("HouId",GasHouMap.get("HouId"));//房源编号
                    billMap.put("HouInfoId",GasHouMap.get("HouInfoId"));//房源详表编号
                    billMap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    billMap.put("Create",ContextUtils.getUserId());//账单创建人
                    billMap.put("ExpTime",GasHouMap.get("EndTime"));//逾期开始时间
                    billMap.put("Status",1);//1待支付


                    if (getInfoMap==null){//只用生成唐巢支出
                        OutLaymap.put("Relation",GasmeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",GasHouMap.get("BillMoney"));//账单金额
                        GasBiMoney = MapUtils.getDouble(OutLaymap,"BiMoney");
                        Integer a1 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a1>0){
                           // result.putSuccess("生成支出账单成功");
                            aaa++;
                        }else{
                            return result.putFailed("生成支出账单失败");
                        }


                    }else{//不仅要生成唐巢支出,也要生成租客账单(该房源已经出租)

                        OutLaymap.put("Relation",GasmeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",GasHouMap.get("BillMoney"));//账单金额
                        OutLaymap.put("StemId",getInfoMap.get("TenId"));//支出关联人编号,有租客
                        Integer a2 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a2>0){
                            //result.putSuccess("生成支出账单成功");
                            aaa++;
                        }else{
                            return result.putFailed("生成支出账单失败");
                        }




                        //先查秘书
                        String StartTime = MapUtils.getString(getInfoMap,"StartTime");//合同的开始时间
                        Map<String,Object> mishuMap =new HashMap<>();
                        mishuMap.put("StartTime",StartTime);
                        mishuMap.put("HouId",GasHouMap.get("HouId"));
                        mishuMap.put("MeterRole",1);
                        Map<String,Object> getHouInfoGas= new HashMap<>();

                        getHouInfoGas= hoGasMeterMapper.getHouInfoGas(mishuMap);//上次抄表人是秘书
                        if (getHouInfoGas==null){
                            mishuMap.put("MeterRole",0);
                            mishuMap.remove("StartTime");
                            getHouInfoGas = hoGasMeterMapper.getHouInfoGas(mishuMap);//上次抄表人租赁顾问

                        }
                        //秘书查不到就差顾问







                      // Map<String,Object> getHouInfoGas = hoGasMeterMapper.getHouInfoGas(GasHouMap);//查询上次抄表人
                      if (MapUtils.getInteger(getHouInfoGas,"MeterRole")==0){//租赁顾问

                          billMap.put("Source",GasmeIdUUID);//账单来源
                          billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                          billMap.put("BiMoney",CompuUtils.mul(CompuUtils.reduce( MapUtils.getDouble(GasHouMap,"ThisMonthRead"),MapUtils.getDouble(getHouInfoGas,"ThisMonthRead")),MapUtils.getDouble(getInfoMap,"GasPricing")));//账单金额,每个租客本次抄表需支付金额
                          GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");

                          Integer a4 =  seTenantBillMapper.addTenantBill(billMap);
                          if (a4>0){
                             // result.putSuccess("生成租客账单成功");
                              aaa++;


                              JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                              Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                              //推送微信模板
                              String touser=ceshiMap.get("uopid").toString();//租客的openid
                              Map<String, TemplateData> param = new HashMap<>();
                              param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的燃气费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                              param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                              param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                              param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                              param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                              log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                              Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));


                          }else{
                              return result.putFailed("生成租客账单失败");
                          }


                      }else if(MapUtils.getInteger(getHouInfoGas,"MeterRole")==1){//秘书

                          billMap.put("Source",GasmeIdUUID);//账单来源
                          billMap.put("BiMoney",GasHouMap.get("BillMoney"));//账单金额,每个租客本次抄表需支付金额
                          GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");
                          billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                          Integer a3 =  seTenantBillMapper.addTenantBill(billMap);
                          if (a3>0){
                              //result.putSuccess("生成租客账单成功");
                              aaa++;

                              JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                              Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                              //推送微信模板
                              String touser=ceshiMap.get("uopid").toString();//租客的openid
                              Map<String, TemplateData> param = new HashMap<>();
                              param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的燃气费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                              param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                              param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                              param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                              param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                              log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                              Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));

                          }else{
                              return result.putFailed("生成租客账单失败");
                          }

                      }

                   }


                    Map<String,Object> GasMap = new HashMap<>();//记录燃不生成账单
                    GasMap.put("term", "2");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    GasMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(GasMap);
                    GasMap.put("GasmeId",GasmeIdUUID);//燃气费抄表编号
                    GasMap.put("BatchId",BatchIdUUID);//批次编号
                    GasMap.put("HouId",GasHouMap.get("HouId"));//房源编号
                    GasMap.put("HouInfoId",GasHouMap.get("HouInfoId"));//房源详表编号
                    GasMap.put("IfOperaType",1);//是否整租0否1是
                    GasMap.put("LastMonthRead",GasHouMap.get("LastMonthRead"));//上次总表数
                    GasMap.put("ThisMonthRead",GasHouMap.get("ThisMonthRead"));//总表数
                    GasMap.put("StaTime",GasHouMap.get("StaTime"));//总表数
                    GasMap.put("EndTime",GasHouMap.get("EndTime"));//总表数
                    GasMap.put("MeterRole",1);//抄表人角色1 服务秘书
                    GasMap.put("BillMoney",GasBiMoney);//账单金额111111111111111111111111
                    GasMap.put("GenerateTime",GenerateTimes);//抄表日期
                    GasMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    GasMap.put("IfApportion",0);//是否需要分摊0否1是
                    GasMap.put("IfGenerate",1);//是否生成账单
                    Integer a3= hoGasMeterMapper.addHoGasMeter(GasMap);//新增燃气抄表记录
                    if (a3>0){
                       // result.putSuccess("新增燃气表成功");
                        aaa++;

                    }else{
                        return result.putFailed("新增燃气表失败");
                    }


                    if(getInfoMap==null){
                        if (aaa==2){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }else {
                        if (aaa==3){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }


                }
                if(a==GasHouList.size()){
                    result.putSuccess("抄表成功");
                }else{
                    return result.putFailed("抄表失败");
                }


            }
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        } finally {
            lock.unlock();
        }
        return result;

    }

    /**
     * 管家退租查询上期燃气费(上期为租赁顾问或者秘书)
     * @param params
     * @return
     */
    @Override
    public JsonResult getLastGasLease(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        return result.put(hoGasMeterMapper.getHouInfoGas(params));
    }
}
